package com.fh.shop.api.pay.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.fh.shop.api.common.ServerResponse;
import com.fh.shop.api.config.AlipayConfig;
import com.fh.shop.api.pay.biz.IPayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@RestController
@RequestMapping("/api/pay")
@Slf4j
public class PayController {

    @Resource(name = "payService")
    private IPayService payService;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private HttpServletResponse response;

    @GetMapping("aliPayPage")
    public String aliPayPage(String orderId) {
        return payService.aliPayPage(orderId);
    }

    /**
     * 支付宝平台 同步调用
     * 跳转到页面
     */
    @GetMapping("/aliReturn")
    public void aliReturn() {
        //获取支付宝GET过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        // 获取支付宝传递参数信息
        Map<String,String[]> requestParams = request.getParameterMap();
        // 把支付宝给你传递的参数信息 放到 params
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
//            //乱码解决，这段代码在出现乱码时使用
//            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        // 验签
        boolean signVerified = false; //调用SDK验证签名
        try {
            signVerified = AlipaySignature.rsaCheckV1(params,
                    AlipayConfig.alipay_public_key,
                    AlipayConfig.charset,
                    AlipayConfig.sign_type);
            //——请在这里编写您的程序（以下代码仅作参考）——
            if(signVerified) {
                // 验签成功,证明是支付宝平台给你发送过来的请求，跳转到支付成功页面
                String total_amount = params.get("total_amount");
                response.sendRedirect("http://localhost:63342/book-api/shop-portal/html/paysuccess.html?price="+total_amount);
            }else {
                // 验签失败
                log.error("验签失败！！！");
            }
        } catch (AlipayApiException | IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 支付宝平台 异步调用
     * 具体的商家的业务
     * success : 成功，支付宝就不会再次发送请求.
     * 不是success,如：failure : 失败，支付宝 就会 再次发送请求，最多发送8次
     *
     */
    @PostMapping("/aliNotify")
    public String aliNotify() {
        Map<String,String[]> requestParams = request.getParameterMap();
        return payService.aliNotify(requestParams);
    }
}
